<?php

namespace app\api\controller;

use think\Db;
use think\Request;

class Ranking extends Common
{
    public function lists(Request $request = null)
    {
        return $this->pass([]);

        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $types = $request->param('types') ?: 3;
        $time = $request->param('time') ?: 1;

        $contain_time = ['', 'd', 'w', 'm', 'y'];

        $config = Db::name('config_ranking')->where(['types' => $types])->find();

        $total = $config['show_count'] - $page * $pagesize;

        if ($total < 0) {
            $total_value = $total * -1;

            if ($total_value >= $pagesize) {
                $pagesize = 0;
            } else {
                $pagesize = $pagesize - $total_value;
            }
        }

        $data = Db::name('ranking_records t1')
            ->field('t1.user_id, t1.to_user, t2.name, t2.head_100 avatar, sum(t1.count) count')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.types' => $types])
            ->whereTime('create_time', $contain_time[$time])
            ->order('count desc')
            ->page($page,$pagesize)->group('t1.user_id')->select();

        $ids = [];
        foreach ($data as $key => $item) {
            $data[$key]['avatar'] = changeUrl($item['avatar']);
            $data[$key]['avatar_2'] = '';

            if ($types == 1) {
                $ids[] = $item['to_user'];
            }
        }

        if ($types == 1) {
            if ($ids) {
                $users = Db::name('user')->where(['id' => ['in', $ids]])->cache(43200)->column('id, name, head_100');
            } else {
                $users = [];
            }

            foreach ($data as $key => $item) {
                $data[$key]['name_2'] = $users[$item['to_user']]['name'] ?? '';
                $data[$key]['avatar_2'] = isset($users[$item['to_user']]['head_100']) ? changeUrl($users[$item['to_user']]['head_100']) : '';
            }
        }

        return $this->pass($data);
    }
}
